﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace GoodStuff.Heartbeat.Core.Monitors
{
    /// <summary>
    /// Implementation of a monitor that detects when a counter is above a certain level for a period of time.
    /// </summary>
    public class AverageHighMonitor : IMonitor
    {
        private float _limit;
        private float _warningLimit;
        private TimeSpan _duration;
        private DateTime? _highSince;

        public AverageHighMonitor(float warningValue, float maxValue, TimeSpan duration)
        {
            _limit = maxValue;
            _warningLimit = warningValue;
            _duration = duration;
        }

        public void Validate(ISensorChannel channel)
        {
            if (channel.Value >= _limit)
            {
                if(!_highSince.HasValue)
                {
                    _highSince = DateTime.Now;
                }

                if (DateTime.Now > _highSince.Value.Add(_duration))
                {
                    State = MonitorState.Failure;
                }
                else
                {
                    State = MonitorState.Warning;
                }
            }
            else
            {
                //reset the counter
                _highSince = null;

                State = MonitorState.Healthy;
            }
        }

        public MonitorState State { get; private set; }
    }
}
